<?php


namespace frontend\controllers;


class common
{
    /**
     * 成功返回接口
     * @param string $error_code
     * @param array $data
     * @param string $msg
     * @return false|string
     * @name cyf
     */
    public static function success($error_code='ok',$data=[],$msg='')
    {
        return [
            'code'=>$error_code,
            'data'=>$data,
            'msg'=>$msg
        ];
    }

    /**
     * 失败返回接口
     * @param string $error_code
     * @param array $data
     * @param string $msg
     * @return false|string
     * @name cyf
     */
    public static function fail($error_code='no',$data=[],$msg='')
    {
        return [
            'code'=>$error_code,
            'data'=>$data,
            'msg'=>$msg
        ];
    }


    /**
     * 加密
     * @param $txt 加密的内容
     * @param string $key 要和解密的一样
     * @return string
     */
    public static function lock_url($txt,$key='2008A'){
        $txt = $txt.$key;
        $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+";
        $nh = rand(0,64);
        $ch = $chars[$nh];
        $mdKey = md5($key.$ch);
        $mdKey = substr($mdKey,$nh%8, $nh%8+7);
        $txt = base64_encode($txt);
        $tmp = '';
        $i=0;$j=0;$k = 0;
        for ($i=0; $i<strlen($txt); $i++) {
            $k = $k == strlen($mdKey) ? 0 : $k;
            $j = ($nh+strpos($chars,$txt[$i])+ord($mdKey[$k++]))%64;
            $tmp .= $chars[$j];
        }
        return urlencode(base64_encode($ch.$tmp));
    }


    /**
     * 解密
     * @param $txt 解密的值
     * @param string $key 加密时的公共key
     * @return string
     */
    public static function unlock_url($txt,$key='2008A')
    {
        $txt = base64_decode(urldecode($txt));
        $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+";
        $ch = $txt[0];
        $nh = strpos($chars,$ch);
        $mdKey = md5($key.$ch);
        $mdKey = substr($mdKey,$nh%8, $nh%8+7);
        $txt = substr($txt,1);
        $tmp = '';
        $i=0;$j=0; $k = 0;
        for ($i=0; $i<strlen($txt); $i++) {
            $k = $k == strlen($mdKey) ? 0 : $k;
            $j = strpos($chars,$txt[$i])-$nh - ord($mdKey[$k++]);
            while ($j<0) $j+=64;
            $tmp .= $chars[$j];
        }

        return trim(base64_decode($tmp),$key);
    }


}